# -*- coding:utf-8 -*-
from fastapi import FastAPI
from typing import Callable
from core.storage import register_mysql, dispose_mysql, RedisStorage
from core.storage import init_create_table


def startup(app: FastAPI) -> Callable:
    """
    FastApi 启动完成事件
    """

    async def app_start() -> None:
        # APP启动完成后触发
        print("-------------  fastapi已启动  -------------")
        # 加载MySQL
        await register_mysql(app)
        # 创建数据库表
        # await init_create_table(app)

        # 加载Redis
        await RedisStorage.init_redis(app)

    return app_start


def stopping(app: FastAPI) -> Callable:
    """
    FastApi 停止事件
    """

    async def stop_app() -> None:
        # APP停止时触发
        await dispose_mysql(app)
        # print("stop_app")
        await RedisStorage.shutdown_redis(app)

    return stop_app


def register_events(app: FastAPI) -> None:
    """
    启动和退出事件定义
    """
    app.add_event_handler("startup", startup(app))
    app.add_event_handler("shutdown", stopping(app))
